import { ref, h } from "vue";
import { useRouter } from "vue-router";
// keepAlive组件
export const keepAliveComponents = new Map();
/**
 * 缓存路由
 */
export const cacheRoutes = ref([] as any);

export const useKeepAlive = () => {
  const router = useRouter();
  /**
   * 存储路由
   */
  const useSetComponent = (path: string, com: object) => {
    const component = {
      name: path,
      render() {
        return h(com);
      },
    };
    cacheRoutes.value.push(path);
    keepAliveComponents.set(path, component);
    return component;
  };
  /**
   * 是否存在当前缓存的组件
   */
  const useHasComponent = (path: string) => keepAliveComponents.has(path);
  /**
   * 获取路由
   */
  const useGetComponent = (path: string) => keepAliveComponents.get(path);
  /**
   * 删除
   */
  const useDeleteComponent = (path: string) => {
    keepAliveComponents.delete(path);
    // index
    const idx = cacheRoutes.value.findIndex((item: string) => item === path);
    if (idx !== -1) {
      cacheRoutes.value.splice(idx, 1);
    }
  };
  /**
   * 返回路由的组件
   */
  const useFormatComponent = (component: object, route: any) => {
    if (component) {
      const path = route?.path;
      const afterComponent = useHasComponent(path)
        ? useGetComponent(path)
        : useSetComponent(path, component);
      return h(afterComponent);
    }
  };

  return {
    useFormatComponent,
    useDeleteComponent,
    useGetComponent,
    cacheRoutes,
  };
};
